package com.xsq.audio.player.playlist

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.media.MediaMetadataCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.xsq.audio.AudioItemData
import com.xsq.audio.IAudioControllerListener
import com.xsq.audio.IAudioSubscriptionCallback
import com.xsq.audio.R
import com.xsq.audio.player.PlayManager
import com.xsq.audio.player.utils.UIUtils

/**
 * 当前专辑音频列表弹窗
 *
 * Created by Shiquan.Xiao on 2023/4/3.
 */
class AudioListDialog : BottomSheetDialogFragment() {

    private var rootView: View? = null

    private lateinit var playModeTv: TextView
    private lateinit var songSumTv: TextView
    private lateinit var playModeIv: ImageView
    private lateinit var clearAllIv: ImageView
    private lateinit var recyclerView: androidx.recyclerview.widget.RecyclerView
    private var musicList: MutableList<AudioItemData> = ArrayList()
    private var mAdapter: PlayListAdapter? = null

    private var mBehavior: BottomSheetBehavior<*>? = null

    private val audioControllerListener: IAudioControllerListener = object : IAudioControllerListener() {

        override fun onPlayChange(
            metadata: MediaMetadataCompat?,
            audioItemList: MutableList<AudioItemData>
        ) {
            showSongs(audioItemList)
        }

    }

    private val audioSubscriptionCallback  = IAudioSubscriptionCallback { audioItemList ->
        showSongs(audioItemList)
    }

    override fun onStart() {
        super.onStart()
        (view?.parent as View).setBackgroundColor(Color.TRANSPARENT)
        //默认全屏展开
        mBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
        super.onCreate(savedInstanceState)
        mAdapter = PlayListAdapter(musicList)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(activity)
        recyclerView.adapter = mAdapter
        recyclerView.scrollToPosition(PlayManager.getCurrentItemPosition())

        initListener()
        mBehavior = BottomSheetBehavior.from(rootView?.parent as View)

        UIUtils.updatePlayModeIcon(playModeIv)

        PlayManager.addIAudioControllerListener(audioControllerListener)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.dialog_audio_list, container, false)
        }
        rootView?.let {
            recyclerView = it.findViewById(R.id.rcv_songs)
            playModeTv = it.findViewById(R.id.tv_play_mode)
            songSumTv = it.findViewById(R.id.tv_song_sum)
            playModeIv = it.findViewById(R.id.iv_play_mode)
            clearAllIv = it.findViewById(R.id.iv_clear_all)
        }
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        return rootView
    }

    private fun initListener() {
        playModeTv.setOnClickListener { view ->
            UIUtils.updatePlayMode(playModeIv, true)
            playModeTv.text = PlayListManager.getPlayMode()
        }
        playModeIv.setOnClickListener { view ->
            UIUtils.updatePlayMode(view as ImageView, true)
            playModeTv.text = PlayListManager.getPlayMode()
        }
        clearAllIv.setOnClickListener { v ->

        }
        mAdapter?.setOnItemClickListener{ pos, oldPos ->
            if (musicList.size > 0) {
                if (pos == oldPos) return@setOnItemClickListener

                if (oldPos != -1) {
                    val data = musicList[oldPos]
                    data.isSelect = false
                    mAdapter?.notifyItemChanged(oldPos)
                }

                val curData = musicList[pos]
                curData.isSelect = true
                mAdapter?.notifyItemChanged(pos)

                PlayManager.playAudioItem(curData)
            }
        }
        PlayManager.subscribe(audioSubscriptionCallback)

    }

    @SuppressLint("SetTextI18n")
    fun showSongs(songs: MutableList<AudioItemData>) {
        musicList = songs
        songSumTv.text = "(${songs.size})"
        playModeTv.text = PlayListManager.getPlayMode()
        mAdapter?.setOldSelectPos(PlayManager.getCurrentItemPosition())
        mAdapter?.setNewAudioList(songs)
        //滚动到正在播放的位置
        recyclerView.scrollToPosition(PlayManager.getCurrentItemPosition())
    }

    override fun onDestroy() {
        super.onDestroy()
        PlayManager.removeIAudioControllerListener(audioControllerListener)
        PlayManager.unsubscribe(audioSubscriptionCallback)
    }

    companion object {
        fun newInstance(): AudioListDialog {
            val args = Bundle()
            val fragment = AudioListDialog()
            fragment.arguments = args
            return fragment
        }
    }

    fun showIt(context: AppCompatActivity) {
        val fm = context.supportFragmentManager
        show(fm, "dialog")
    }

}